package com.playplus.utils.inapp
{
	//import com.freshplanet.nativeExtensions.InAppPurchase;
	//import com.freshplanet.nativeExtensions.InAppPurchaseEvent;
	
	import com.adobe.ane.productStore.Product;
	import com.adobe.ane.productStore.ProductEvent;
	import com.adobe.ane.productStore.ProductStore;
	import com.adobe.ane.productStore.Transaction;
	import com.adobe.ane.productStore.TransactionEvent;
	import com.playplus.utils.Base64;
	
	import flash.events.Event;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	
	public class InAppPurchaseManager extends InApp
	{
		private var mInApp:ProductStore;
		
		public function InAppPurchaseManager()
		{
		}
		
		override public function init():void
		{
			if(!mInApp){
				mInApp = new ProductStore();
			}
			initEvent();
			trace("mInApp.available  : " + mInApp.available);
			//trace("mInApp.isSupported  : " + ProductStore.isSupported;);
			
			var vector:Vector.<String> = new Vector.<String>(2);
			
			vector[0] = "xxx.xxx.xxx.coin1000";
			
			vector[1] = "xxx.xxx.xxx.coin2000";
			
			//vector[2] = "1234897";
			
			mInApp.requestProductsDetails(vector);
			
			
		}
		
		protected function initEvent():void
		{
			
			mInApp.addEventListener(ProductEvent.PRODUCT_DETAILS_SUCCESS, onInAppPurchaseSuccessfull);
			mInApp.addEventListener(ProductEvent.PRODUCT_DETAILS_FAIL, onInAppPurchaseError);
			mInApp.addEventListener(TransactionEvent.PURCHASE_TRANSACTION_SUCCESS, purchaseTransactionSucceeded);
			mInApp.addEventListener(TransactionEvent.PURCHASE_TRANSACTION_CANCEL, purchaseTransactionCanceled);
			mInApp.addEventListener(TransactionEvent.PURCHASE_TRANSACTION_FAIL, purchaseTransactionFailed);
			mInApp.addEventListener(TransactionEvent.RESTORE_TRANSACTION_SUCCESS, restoreTransactionSucceeded);
			mInApp.addEventListener(TransactionEvent.RESTORE_TRANSACTION_FAIL, restoreTransactionFailed);
			mInApp.addEventListener(TransactionEvent.RESTORE_TRANSACTION_COMPLETE,  restoreTransactionCompleted);
			
			/*
			mInApp.addEventListener(InAppPurchaseEvent.PURCHASE_ENABLED, onInAppPurchaseEnabled);
			mInApp.addEventListener(InAppPurchaseEvent.PURCHASE_DISABLED, onInAppPurchaseDisabled);
			mInApp.addEventListener(InAppPurchaseEvent.PRODUCT_INFO_RECEIVED, onProductInfoReceived);
			mInApp.addEventListener(InAppPurchaseEvent.PRODUCT_INFO_ERROR, onProductInfoError);
			*/
		}
		
		protected function removeEvent():void
		{
			/*
			mInApp.removeEventListener(InAppPurchaseEvent.PURCHASE_SUCCESSFULL, onInAppPurchaseSuccessfull);
			mInApp.removeEventListener(InAppPurchaseEvent.PURCHASE_ERROR, onInAppPurchaseError);
			mInApp.removeEventListener(InAppPurchaseEvent.PURCHASE_ENABLED, onInAppPurchaseEnabled);
			mInApp.removeEventListener(InAppPurchaseEvent.PURCHASE_DISABLED, onInAppPurchaseDisabled);
			mInApp.removeEventListener(InAppPurchaseEvent.PRODUCT_INFO_RECEIVED, onProductInfoReceived);
			mInApp.removeEventListener(InAppPurchaseEvent.PRODUCT_INFO_ERROR, onProductInfoError);
			*/
		}
		
		private function onInAppPurchaseSuccessfull(e:ProductEvent):void
		{
			trace("in productDetailsSucceeded "+e);
			
			var i:uint=0;
			
			while(e.products && i < e.products.length)
				
			{
				
				var p:Product = e.products[i];
				
				//prodSuccess.appendText("\nTITLE: " + p.title + "\nDescription: " + p.description + "\nIdentifier : " + p.identifier + "PriceLocale : " + p.priceLocale + "\nPrice: " + p.price);
				
				trace("title : "+p.title);
				
				trace("description: "+p.description);
				
				trace("identifier: "+p.identifier);
				
				trace("priceLocale: "+p.priceLocale);
				
				trace("price :"+p.price);
				
				i++;
				
			}
		}
		
		private function onInAppPurchaseError(e:ProductEvent):void
		{
			trace("in productDetailsFailed"+e);
			
			var i:uint=0;
			
			while(e.invalidIdentifiers && i < e.invalidIdentifiers.length)
				
			{
				
				trace(e.invalidIdentifiers[i]);
				
				i++;
				
			}
		}
		
		protected function restoreTransactionSucceeded(e:TransactionEvent):void{
			
			trace("in restoreTransactionSucceeded" +e);
			
			//val= "Restore Success";
			
			//restoreTxt.text = val;
			
			var i:uint=0;
			
			while(e.transactions && i < e.transactions.length)
				
			{
				
				var t:Transaction = e.transactions[i];
				
				printTransaction(t);
				
				i++;
				
				
				
				trace("FinishTransactions" + t.identifier);
				
				mInApp.addEventListener(TransactionEvent.FINISH_TRANSACTION_SUCCESS, finishTransactionSucceeded);
				
				mInApp.finishTransaction(t.identifier);
				
			}
			
			
			
			getPendingTransaction(mInApp);
			
		}
		
		
		protected function finishTransactionSucceeded(e:TransactionEvent):void{
			
			trace("in finishTransactionSucceeded" +e);
			
			var i:uint=0;
			var isSuccess:Boolean = false;
			while(e.transactions && i < e.transactions.length)
				
			{
				
				var t:Transaction = e.transactions[i];
				
				if(t.receipt){
					trace("t.receipt  : " + t.receipt);
					isSuccess = true;
				}
				printTransaction(t);
				
				i++;
				
			}
			
			if(!isSuccess){
				trace("fail payment");
				cancle();
			}else{
				complete();
			}
			
		}	
		
		protected function restoreTransactionFailed(e:TransactionEvent):void{
			
			trace("in restoreTransactionFailed" +e);
			
			//val="Restore Fail";
			
			//restoreTxt.text = val;
			
		}
		
		public function getPendingTransaction(prdStore:ProductStore):void
			
		{
			
			trace("pending transaction");
			
			var transactions:Vector.<Transaction> = prdStore.pendingTransactions; 
			
			var i:uint=0;
			
			while(transactions && i<transactions.length)
				
			{
				
				var t:Transaction = transactions[i];
				
				printTransaction(t);
				
				i++;
				
			}
			
		}
		
		public function printTransaction(t:Transaction):void
			
		{
			
			trace("-------------------in Print Transaction----------------------");
			
			trace("identifier :"+t.identifier);
			
			trace("productIdentifier: "+ t.productIdentifier);
			
			trace("productQuantity: "+t.productQuantity);
			
			trace("date: "+t.date);
			
			trace("receipt: "+t.receipt);
			
			trace("error: "+t.error);
			
			trace("originalTransaction: "+t.originalTransaction);
			
			if(t.originalTransaction)
				
				printTransaction(t.originalTransaction);
			
			trace("---------end of print transaction----------------------------");
			
		}	
		
		protected function restoreTransactionCompleted(e:TransactionEvent):void{
			
			trace("in restoreTransactionCompleted" +e);
			
			//val = "Restore Complete";
			
			//restoreTxt.text = val;
			
		}

		
		
		protected function purchaseTransactionSucceeded(e:TransactionEvent):void
			
		{
			
			trace("in purchaseTransactionSucceeded" +e);
			
			var i:uint=0;
			
			var t:Transaction;
			
			while(e.transactions && i < e.transactions.length)
				
			{
				
				t = e.transactions[i];
				
				printTransaction(t);
				
				i++;
				
				var Base:Base64=new Base64();
				
				var encodedReceipt:String = Base64.Encode(t.receipt);
				
				var req:URLRequest = new URLRequest("https://buy.itunes.apple.com/verifyReceipt");
				
				req.method = URLRequestMethod.POST;
				
				req.data = "{\"receipt-data\" : \""+ encodedReceipt+"\"}";
				//trace("req.data  : " + req.data);
				var ldr:URLLoader = new URLLoader(req);
				
				ldr.load(req);
				
				ldr.addEventListener(Event.COMPLETE,function(e:Event):void{
					
					var mData:Object = JSON.parse(ldr.data);
					//trace("LOAD COMPLETE: " + ldr.data);
					//trace("ldr.data.status  : " + mData.status);
					if(mData.status && mData.status == 21007){
						req.url = "https://sandbox.itunes.apple.com/verifyReceipt";
						ldr.load(req);
					}else{
						mInApp.addEventListener(TransactionEvent.FINISH_TRANSACTION_SUCCESS, finishTransactionSucceeded);
						
						mInApp.finishTransaction(t.identifier);
					}
					
					
				});
				
				
				
				trace("Called Finish on/Finish Transaction " + t.identifier); 
				
			}
			
			getPendingTransaction(mInApp);
			
		}
		
		
		
		protected function purchaseTransactionCanceled(e:TransactionEvent):void{
			
			trace("in purchaseTransactionCanceled"+e);
			
			var i:uint=0;
			
			while(e.transactions && i < e.transactions.length)
				
			{
				
				var t:Transaction = e.transactions[i];
				
				printTransaction(t);
				
				i++;
				
				trace("FinishTransactions" + t.identifier);
				
				mInApp.addEventListener(TransactionEvent.FINISH_TRANSACTION_SUCCESS, finishTransactionSucceeded);
				
				mInApp.finishTransaction(t.identifier);
				
			}
			
			getPendingTransaction(mInApp);
			
			cancle();
			
		}
		
		
		
		protected function purchaseTransactionFailed(e:TransactionEvent):void
			
		{
			
			trace("in purchaseTransactionFailed"+e);
			
			var i:uint=0;
			
			while(e.transactions && i < e.transactions.length)
				
			{
				
				var t:Transaction = e.transactions[i];
				
				printTransaction(t);
				
				i++;
				
				trace("FinishTransactions" + t.identifier);
				
				mInApp.addEventListener(TransactionEvent.FINISH_TRANSACTION_SUCCESS, finishTransactionSucceeded);
				
				mInApp.finishTransaction(t.identifier);
				
			}
			
			
			
			getPendingTransaction(mInApp);
			
			cancle();
		}
		
		
		
		private function onProductInfoError(e:Event):void
		{
			trace("onProductInfoError  ");
		}
		
		public function inAppRemove():void
		{
			
		}
		
		override public function buyItem(pProductID:String):void
		{
			//mInApp.userCanMakeAPurchase();
			//mInApp.init();
			//mInApp.userCanMakeAPurchase();
			//mInApp.getProductsInfo(["com.playplus.birdyboom.1000", "com.playplus.birdyboom.2000"]);
			trace("buyItem");
			mProductId = pProductID;
			mInApp.makePurchaseTransaction(pProductID,1);
			
		}
		
	}
}